package com.microframework.boot.collect.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson2.JSONObject;
import com.jfinal.plugin.activerecord.Page;
import com.microframework.base.web.page.PageQuery;
import com.microframework.boot.collect.model.domain.DataSourceConfig;
import com.microframework.boot.collect.service.IDataSourceConfigService;
import com.microframework.boot.collect.service.IHttpApiService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class DataSourceConfigServiceImpl implements IDataSourceConfigService {
	
	@Autowired
	private IHttpApiService httpApiService;
	
	@Override
	public Page<DataSourceConfig> pages(PageQuery<DataSourceConfig> pageQuery) {
		try {
			StringBuilder sqlBuilder = new StringBuilder("FROM " + DataSourceConfig.TABLE_NAME + " WHERE 1=1");
			List<Object> params = new ArrayList<>();

			DataSourceConfig query = pageQuery.getQuery();
			if (query != null) {
				// 构建查询条件

				if (StringUtils.hasText(query.getName())) {
					sqlBuilder.append(" AND name LIKE ?");
					params.add("%" + query.getName() + "%");
				}

				if (StringUtils.hasText(query.getType())) {
					sqlBuilder.append(" AND type = ?");
					params.add(query.getType());
				}

				if (query.getStatus() != null) {
					sqlBuilder.append(" AND status = ? ");
					params.add(query.getStatus());
				}
			}

			// 设置排序
			String orderBy = StringUtils.hasText(pageQuery.getOrderBy()) ? pageQuery.getOrderBy() : " modify_time";
			String orderDirection = StringUtils.hasText(pageQuery.getOrderDirection()) ? pageQuery.getOrderDirection()
					: "desc";
			sqlBuilder.append(" ORDER BY " + orderBy + " " + orderDirection);
			String select = "select id,name,type,status,description,modify_time ";
			return DataSourceConfig.dao.paginate(pageQuery.getPageNumber(), pageQuery.getPageSize(), select,
					sqlBuilder.toString(), params.toArray());
		} catch (Exception e) {
			log.error("查询列表异常{}", e.getMessage());
			return new Page<DataSourceConfig>(new ArrayList<>(), 1, 10, 0, 0);
		}
	}

	@Override
	public JSONObject check(String id) throws Exception {
		DataSourceConfig dataSourceConfig=DataSourceConfig.dao.findById(id);
		if(dataSourceConfig==null) {
			throw new Exception("无效得数据源Id.");
		}
		return httpApiService.check(dataSourceConfig);
	}

}
